package cn.silver.module.quartz.util;

import cn.silver.framework.core.enums.SystemResultEnums;
import cn.silver.framework.core.utils.BeanUtils;
import cn.silver.framework.core.utils.DateUtils;
import cn.silver.framework.core.utils.SpringUtils;
import cn.silver.module.quartz.bean.JobLogBean;
import cn.silver.module.quartz.domain.SysJob;
import cn.silver.module.quartz.service.ISysJobLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;

import java.util.Date;

/**
 * 抽象quartz调用
 *
 * @author Silver.Zhou
 */
@Slf4j
public abstract class AbstractQuartzJob implements Job {

    /**
     * 线程本地变量
     */
    private static final ThreadLocal<Date> THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public void execute(JobExecutionContext context) {
        SysJob sysJob = new SysJob();
        BeanUtils.copyBeanProp(sysJob, context.getMergedJobDataMap().get(ScheduleUtils.TASK_PROPERTIES));
        try {
            before(context, sysJob);
            doExecute(context, sysJob);
            after(context, sysJob, null);
        } catch (Exception e) {
            log.error("任务执行异常  - ：", e);
            after(context, sysJob, e);
        }
    }

    /**
     * 执行前
     *
     * @param context 工作执行上下文对象
     * @param job     系统计划任务
     */
    protected void before(JobExecutionContext context, SysJob job) {
        log.info("定时任务执行前操作，任务分组：{}，任务编号：{}，任务名称：{}",
                job.getGroup(), job.getCode(), job.getName());
        log.info("设置任务开始时间");
        THREAD_LOCAL.set(new Date());
    }

    /**
     * 执行后
     *
     * @param context 工作执行上下文对象
     * @param job     系统计划任务
     */
    protected void after(JobExecutionContext context, SysJob job, Exception e) {
        log.info("任务执行完成操作，任务分组：{}，任务编号：{}，任务名称：{}",
                job.getGroup(), job.getCode(), job.getName());
        Date startTime = THREAD_LOCAL.get();
        Date endTime = DateUtils.getNowDate();
        long consume = endTime.getTime() - startTime.getTime();
        THREAD_LOCAL.remove();
        log.info("任务开始时间：{}，完成时间：{}，执行耗时：{}毫秒", DateUtils.dateformat(startTime), DateUtils.dateformat(startTime), consume);
        final JobLogBean jobLog = new JobLogBean();
        jobLog.setJobId(job.getId());
        jobLog.setJobName(job.getName());
        jobLog.setJobGroup(job.getGroup());
        jobLog.setInvoke(job.getInvoke());
        jobLog.setStartTime(startTime);
        jobLog.setStopTime(endTime);
        jobLog.setCostTime(consume);
        jobLog.setContent(jobLog.getJobName() + " 总共耗时：" + consume + "毫秒");
        if (e != null) {
            jobLog.setResult(SystemResultEnums.FAIL.getCode());
            String errorMsg = StringUtils.substring(e.getMessage(), 0, 2000);
            jobLog.setMessage(errorMsg);
        } else {
            jobLog.setResult(SystemResultEnums.SUCCESS.getCode());
        }
        // 写入数据库当中
        SpringUtils.getBean(ISysJobLogService.class).insert(jobLog);
    }

    /**
     * 执行方法，由子类重载
     *
     * @param context 工作执行上下文对象
     * @param sysJob  系统计划任务
     * @throws Exception 执行过程中的异常
     */
    protected abstract void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception;
}
